import React, { Component } from 'react';
import { Button, Icon, Input, Table, message, Popconfirm, Tooltip, Empty } from 'antd';
import EmptyDataImg from '@images/empty-data-blue.png';
import VulnerabilityModal from './components/vulnerability-modal';
import {
  getVulnerabilityList,
  addVulnerability,
  deleteVulnerability,
  modVulnerability
} from '@api/task';
import _ from 'lodash';
import './index.less';

const prefixCls = 'vulnerability-manage';
const Search = Input.Search;

const VulnerabilityTypeMap = {
  port: '端口',
  component: '组件',
  service: '服务'
};

class VulnerabilityManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      filter: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      count: 0,
      loading: false,
      modalVisible: false,
      confirmLoading: false,
      rowData: {}
    };
  }

  componentDidMount() {
    this.getVulnerabilityList();
  }

  getVulnerabilityList = () => {
    const filter = _.clone(this.state.filter);
    if (filter.search) {
      filter.search = filter.search.replace(/\\/g, '\\\\');
      filter.search = filter.search.replace(/\|/g, '\\|');
    }
    this.setState({ loading: true });
    getVulnerabilityList(filter)
      .then(res => {
        const count = _.get(res, 'data.data.count', 0);
        const total = _.get(res, 'data.data.total', 0);
        const data = _.get(res, 'data.data.list', []);
        this.setState({ count, total, data, loading: false });
      })
      .catch(() => {
        message.error('获取列表失败');
        this.setState({ loading: false });
      });
  };

  wrapChangeModalVisible = (visible, rowData = {}) => {
    this.setState({
      modalVisible: visible,
      rowData
    });
  };

  onClickSubmit = (type, body) => {
    this.setState({ confirmLoading: true });
    let msgType = body.type;
    if (type === 'add') {
      addVulnerability(body)
        .then(() => {
          message.success('添加成功');
          this.setState({ confirmLoading: false }, () => {
            this.wrapChangeModalVisible(false);
            this.getVulnerabilityList();
          });
        })
        .catch(res => {
          const msg = _.get(res, 'message', '');
          if (msg === '该脆弱项已存在') {
            message.warn(`您已添加过该${VulnerabilityTypeMap[msgType]}，无需重复添加`);
          } else {
            message.error('添加失败');
          }
          this.setState({ confirmLoading: false });
        });
    } else if (type === 'edit') {
      delete body.type;
      modVulnerability(body)
        .then(() => {
          message.success('编辑成功');
          this.setState({ confirmLoading: false }, () => {
            this.wrapChangeModalVisible(false);
            this.getVulnerabilityList();
          });
        })
        .catch(res => {
          const msg = _.get(res, 'message', '');
          if (msg === '该脆弱项已存在') {
            message.warn(`您已添加过该${VulnerabilityTypeMap[msgType]}，无需重复添加`);
          } else {
            message.error('编辑失败');
          }
          this.setState({ confirmLoading: false });
        });
    }
  };

  deleteVulnerability = id => {
    // eslint-disable-next-line
    deleteVulnerability({ vulner_id: id })
      .then(() => {
        message.success('删除成功');
        this.getVulnerabilityList();
      })
      .catch(() => {
        message.error('删除失败');
      });
  };

  onSearchChange = e => {
    let { filter } = this.state;
    filter.search = e.target.value;
    this.setState({ filter });
  };

  onTableChange = (pagination, filter) => {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0;
    const { filter: originFilter } = this.state;
    const { current, pageSize } = pagination;

    originFilter.page = current;
    originFilter.pageSize = pageSize;

    this.setState(
      {
        filter: { ...originFilter, ...filter }
      },
      this.getVulnerabilityList
    );
  };

  render() {
    const {
      filter,
      loading,
      total,
      count,
      data,
      modalVisible,
      confirmLoading,
      rowData
    } = this.state;
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        width: '25%'
      },
      {
        title: '类型',
        dataIndex: 'type',
        width: '30%',
        className: 'vulner-type',
        render: key => VulnerabilityTypeMap[key],
        filters: [
          { text: '端口', value: 'port' },
          { text: '组件', value: 'component' },
          { text: '服务', value: 'service' }
        ],
        filterMultiple: false,
        filteredValue: filter.type && filter.type.length !== 0 ? filter.type : []
      },
      {
        title: '配置方式',
        dataIndex: 'is_build_in',
        width: '30%',
        className: 'vulner-is-build-in',
        render: isBuildIn => (isBuildIn ? '系统默认' : '自定义'),
        filters: [{ text: '系统默认', value: true }, { text: '自定义', value: false }],
        filterMultiple: false,
        filteredValue:
          filter.is_build_in && filter.is_build_in.length !== 0 ? filter.is_build_in : []
      },
      {
        title: '操作',
        render: item => (
          <div>
            <a className="be-color" onClick={() => this.wrapChangeModalVisible(true, item)}>
              编辑
            </a>
            <Popconfirm
              placement="bottomRight"
              title={'确定删除吗'}
              onConfirm={() => this.deleteVulnerability(item._id)}
              okText="确定"
              cancelText="取消"
            >
              <a style={{ marginLeft: 10, color: '#F04038' }}>删除</a>
            </Popconfirm>
          </div>
        )
      }
    ];

    const pagination = {
      total: count,
      current: filter.page,
      pageSize: filter.pageSize,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showSizeChanger: true,
      showTotal: num => `共 ${num} 条`,
      size: 'small'
    };

    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>
          关键监控配置
          <Tooltip
            className="info"
            placement="right"
            overlayClassName={`${prefixCls}-page-title-desc`}
            title="您可以根据实际情况自行配置高危端口、高危服务或者经常出现漏洞但厂商不再维护的组件。系统在执行资产探测和漏洞普查任务时，如果发现列表中的端口、服务和组件，会进行风险提示和告警通知，同时也会在仪表盘显示监控信息。"
          >
            <Icon type="exclamation-circle" />
          </Tooltip>
        </div>

        <div className={`${prefixCls}-operate`}>
          <div>
            <Button type="primary" onClick={() => this.wrapChangeModalVisible(true, {})}>
              <Icon type="plus-circle" />
              添加名单
            </Button>
            <VulnerabilityModal
              modalVisible={modalVisible}
              closeModal={() => this.wrapChangeModalVisible(false)}
              onClickSubmit={this.onClickSubmit}
              confirmLoading={confirmLoading}
              rowData={rowData}
            />
          </div>
          <div>
            <Search
              value={filter.search}
              enterButton
              placeholder="请输入名称"
              onChange={this.onSearchChange}
              onSearch={value => {
                let search = value.toString();
                filter.search = search;
                filter.page = 1;
                this.setState({ filter }, this.getVulnerabilityList);
              }}
            />
          </div>
        </div>
        {total ? (
          <div>
            <div className={`${prefixCls}-header-count`}>共有 “{count}” 个名单</div>
            <Table
              loading={loading}
              columns={columns}
              pagination={pagination}
              dataSource={data}
              onChange={this.onTableChange}
            />
          </div>
        ) : (
          <Empty
            image={EmptyDataImg}
            imageStyle={{
              margin: '120px 0 24px',
              height: 296
            }}
            description={
              <div>
                <span style={{ color: '#2A2B30' }}>您还未创建过脆弱项</span>
                <p style={{ marginTop: 8, color: '#999EA8' }}>
                  探测到对应指纹会出发告警事件，您可以根据实际情况自行配置高危端口以及厂商不在维护的组件
                </p>
              </div>
            }
          />
        )}
      </div>
    );
  }
}

export default VulnerabilityManage;
